import React from 'react';
import { X, Plus } from 'lucide-react';
import { useApp } from '../../../contexts/AppContext';
import clsx from 'clsx';
import { Tab } from '../types';

interface TabBarProps {
  onNewTab: () => void;
}

export function TabBar({ onNewTab }: TabBarProps) {
  const { state, dispatch } = useApp();

  const handleCloseTab = (tabId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    dispatch({ type: 'CLOSE_TAB', payload: tabId });
  };

  const handleSwitchTab = (tabId: string) => {
    dispatch({ type: 'SWITCH_TAB', payload: tabId });
  };

  return (
    <div className="flex items-center bg-gray-100 border-b border-gray-200 px-2">
      <button
        onClick={onNewTab}
        className="p-2 mr-2 text-gray-600 hover:bg-gray-200 rounded"
        title="新建标签页"
      >
        <Plus size={16} />
      </button>

      <div className="flex-1 flex overflow-x-auto">
        {state.tabs.map((tab) => (
          <div
            key={tab.id}
            onClick={() => handleSwitchTab(tab.id)}
            className={clsx(
              'flex items-center min-w-[160px] max-w-[240px] px-3 py-2 mr-1 border rounded-t cursor-pointer',
              tab.isActive
                ? 'bg-white border-gray-300 border-b-white'
                : 'bg-gray-50 border-transparent hover:bg-gray-200'
            )}
          >
            <span className="flex-1 truncate text-sm">
              {tab.title || '新建标签页'}
            </span>
            <button
              onClick={(e) => handleCloseTab(tab.id, e)}
              className="ml-2 p-1 hover:bg-gray-300 rounded"
              title="关闭标签页"
            >
              <X size={12} />
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}